package com.spring.sunflower.common

import android.text.TextUtils
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.TimeUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseActivity
import com.spring.sunflower.bean.AccountMoneyBean
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.dialog.BindPhoneDialog
import com.spring.sunflower.dialog.OnPermissionIntroClickListener
import com.spring.sunflower.util.AppUtils
import java.text.SimpleDateFormat

/**
 * Created by Kevin on 2021/8/30<br/>
 *
 * Describe:<br/>
 */
class WithDrawActivity : BaseActivity<WithDrawPresenter>(), CommonContract.WithDrawView,
    View.OnClickListener {
    private var userID = ""
    private var mobilePhoneNum = ""
    private var tvMoney: TextView? = null
    private var tvMoneyRMB: TextView? = null
    private var etWithdraw: EditText? = null
    private var tvWithdrawAll: TextView? = null
    private var etAlipayAccount: EditText? = null
    private var etRealName: EditText? = null
    private var etPhoneCode: EditText? = null
    private var tvGetPhoneCode: TextView? = null
    private var tvDone: TextView? = null
    private var ivTip: ImageView? = null
    private var tvRule: TextView? = null
    private var tempRMB = 0.0
    private var hasApplyWithDraw = false//一天只能申请一次
    private var tempMobile = ""
    override fun getLayoutID(): Int = R.layout.activity_withdraw

    override fun setPresenter(): WithDrawPresenter = WithDrawPresenter(this)

    override fun initView() {
        userID = getField(Constant.KEY_USERID, "")
        mobilePhoneNum = getField(Constant.KEY_MOBILE, "")
        val applyWithdraw = getField(Constant.KEY_APPLY_WITHDRAW, "")
        hasApplyWithDraw = if (TextUtils.isEmpty(applyWithdraw)) {
            false
        } else {
            val thisDay =
                TimeUtils.millis2String(System.currentTimeMillis(), SimpleDateFormat("yyyy/MM/DD"))
            applyWithdraw.equals(thisDay)
        }
        tvTitle!!.text = "提现"
        tvFunctionX!!.text = "提现记录"

        mPresenter.getAccountMoneyInfo(userID)

        tvMoney = findViewById(R.id.tvMoney)
        tvMoneyRMB = findViewById(R.id.tvMoneyRMB)
        etWithdraw = findViewById(R.id.etWithdraw)
        tvWithdrawAll = findViewById(R.id.tvWithdrawAll)
        etAlipayAccount = findViewById(R.id.etAliPayAccount)
        etRealName = findViewById(R.id.etRealName)
        etPhoneCode = findViewById(R.id.etPhoneCode)
        tvGetPhoneCode = findViewById(R.id.tvGetCode)
        tvDone = findViewById(R.id.tvDone)
        ivTip = findViewById(R.id.ivTip)
        tvRule = findViewById(R.id.tvRule)
        if (hasApplyWithDraw) {
            tvDone!!.setBackgroundResource(R.drawable.ic_btn_bg_click_disable)
        }
        tvWithdrawAll?.setOnClickListener(this)
        tvGetPhoneCode?.setOnClickListener(this)
        tvDone?.setOnClickListener(this)
        tvFunctionX?.setOnClickListener {
            startNewActivity(WithdrawRecordActivity::class.java)
        }
        ivTip?.setOnClickListener {
            showHelpDialog(
                "帮助",
                getString(R.string.withdraw_help), null
            )

        }
        tvRule?.setOnClickListener {
            showHelpDialog(
                "提现规则",
                getString(R.string.withdraw_rules), null
            )
        }
    }

    override fun showAccountMoneyInfo(data: AccountMoneyBean.DatasBean?) {
//        tvMoney!!.text = data!!.integral.toString()
        tvMoney!!.text = data!!.amount.toString()
        tvMoneyRMB!!.text = " (￥${data?.amount})"
        tempRMB = data!!.amount
        if (null != data!!.account) {
            etAlipayAccount?.setText(data!!.account)
        }
        if (null != data!!.realName) {
            etRealName?.setText(data!!.realName)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvWithdrawAll -> {
                val money = tvMoney!!.text.trim().toString()
                if (tempRMB < 50) {
                    showToast("可提现金额低于50元，无法提现")
                    return
                }
                val x = (tempRMB / 50).toInt()
                val realRMB = (x * 50).toString()
                etWithdraw!!.setText(realRMB)
                etWithdraw!!.setSelection(realRMB.length)
            }
            R.id.tvGetCode -> {
                val aliAccount = etAlipayAccount!!.text.toString().trim()
                val amount = etWithdraw!!.text.toString().trim()
                val realName = etRealName!!.text.toString().trim()
                if (TextUtils.isEmpty(amount)) {
                    showToast("提现金额不能为空")
                    return
                }
                if (TextUtils.isEmpty(aliAccount)) {
                    showToast("支付宝账号不能为空")
                    return
                }
                if (TextUtils.isEmpty(realName)) {
                    showToast("姓名不能为空")
                    return
                }
                if (TextUtils.isEmpty(mobilePhoneNum) || mobilePhoneNum.length != 11
                    || !AppUtils.isValidPhoneNum(mobilePhoneNum)
                ) {
                    showBindPhoneDialog()
                    return
                } else {
                    mPresenter.requestAuthCode(mobilePhoneNum, "0")
                }
//                val aliAccount = etAlipayAccount!!.text.toString().trim()
//                printD("length=${aliAccount.length},isValid=${AppUtils.isValidPhoneNum(aliAccount)}")
//                if (aliAccount.length != 11 || !AppUtils.isValidPhoneNum(aliAccount)) {
//                    showToast("支付宝账号不是有效手机号")
//                    return
//                }
            }
            R.id.tvDone -> {
                if (hasApplyWithDraw) {
                    showToast("今日提现次数已用完")
                    return
                }
                val aliAccount = etAlipayAccount!!.text.toString().trim()
                val amount = etWithdraw!!.text.toString().trim()
                val code = etPhoneCode!!.text.toString().trim()
                val realName = etRealName!!.text.toString().trim()
                if (TextUtils.isEmpty(amount)) {
                    showToast("提现金额不能为空")
                    return
                }
                if (TextUtils.isEmpty(aliAccount)) {
                    showToast("支付宝账号不能为空")
                    return
                }
                if (TextUtils.isEmpty(code)) {
                    showToast("验证码不能为空")
                    return
                }
                if (TextUtils.isEmpty(realName)) {
                    showToast("姓名不能为空")
                    return
                }
                if ((amount.toDouble() % 50) != 0.0) {
                    showToast("填写提现金额错误，请查看《提现规则》")
                    return
                }
                if (!AppUtils.isValidEmail(aliAccount) || !AppUtils.isValidPhoneNum(aliAccount)) {
                    showToast("支付宝账号不是有效格式")
                    return
                }
                var map = HashMap<String, String>()
                map["alipay"] = aliAccount
                map["amount"] = amount
                map["code"] = code
                map["memberId"] = userID
                map["realName"] = realName
                showNoticeDialog(
                    "提现确认提示",
                    "提现账户为：${aliAccount}",
                    "确定提现到该账户吗？确定前请仔细核验账户是否正确",
                    "确定",
                    object : OnPermissionIntroClickListener {
                        override fun onClickOK() {
                            mPresenter.applyWithdraw(map)
                        }
                    })
            }
        }
    }

    override fun requestFinish() {
        super.requestFinish()
        val millis2String =
            TimeUtils.millis2String(System.currentTimeMillis(), SimpleDateFormat("yyyy/MM/DD"))
        saveField(Constant.KEY_APPLY_WITHDRAW, millis2String)
        showToast("申请成功，已为您提交审核")
        finish()
    }

    private fun showBindPhoneDialog() {
        val dialog = BindPhoneDialog(this)
        dialog.setOnBindPhoneListener(object : BindPhoneDialog.OnBindPhoneListener {
            override fun onBindClick(phoneNum: String, code: String) {
                tempMobile = phoneNum
                mPresenter.bindPhone(phoneNum, code)
            }

            override fun onGetCodeClick(phoneNum: String) {
                mPresenter.requestAuthCode(phoneNum, "0")
            }


            override fun onCreateView() {
            }

        })
        XPopup.Builder(this)
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
//            .isRequestFocus(false)
            .dismissOnTouchOutside(false)
            .dismissOnBackPressed(false)
            .asCustom(dialog)
            .show()
    }

    override fun bindSuccess() {
        mobilePhoneNum = tempMobile
        showToast("绑定手机号成功")
    }
}